package com.chuanyang.driverh.mainhome;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainhome.adapter.GoodsForAssignWaybilDetailAdapter;
import com.chuanyang.driverh.mainorder.DeliveryOrderActivity;
import com.chuanyang.driverh.mainorder.SureUnLoadOverActivity;
import com.chuanyang.driverh.mainother.LookPhotoDetailActivity;
import com.chuanyang.driverh.response2.ResultWaybilInfoTop;
import com.chuanyang.driverh.responseresult.LookWaybillDetailData;
import com.chuanyang.driverh.responseresult.LookWaybillDetailResult;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class WaybilDetailActivity extends BaseTitleActivity {

    private TextView tv_waybill_no;
    private TextView tv_date;
    private TextView tv_driver_name;
    private TextView tv_plate_no;
    private TextView tv_order_status;
    private TextView tv_tel;
    private TextView tv_tel_dial;
    private TextView tv_gua_weight;
    private TextView tv_shi_weight;
    private TextView tv_gua_num;
    private TextView tv_shi_num;
    private TextView tv_all_price;
    private ListView lv_goods;
    private TextView tv_confirm;
    private LinearLayout ll_photo_out;
    private LinearLayout ll_photo;
    private Dialog dialog;

    private String waybilId;
    private String orderId;
    //0,消息进入，不显示按钮和状态，2派单 查看派单-运单详情，不显示状态,//3,代运实发-查看派单-运单列表，显示运输校核 ,4代运实发运单地图查看
    //5,代运实发-查看派单-运单列表，显示运输校核 ,并且可以删除照片，上传回单，个人接的单子。
    //6代运实发-查看派单-运单列表，显示运输校核 ,并且可以删除照片，上传回单，给自己分配的单子。
    private int type;
    @Override
    protected int getContentResId() {
        return R.layout.home_act_waibil_detail_no_top;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        View view=View.inflate(activityContext,R.layout.home_item_waybil_top,null);

        tv_waybill_no=(TextView)view.findViewById(R.id.tv_waybill_no);
        tv_date=(TextView)view.findViewById(R.id.tv_date);
        tv_driver_name=(TextView)view.findViewById(R.id.tv_driver_name);
        tv_plate_no=(TextView)view.findViewById(R.id.tv_plate_no);
        tv_order_status=(TextView)view.findViewById(R.id.tv_order_status);
        tv_tel=(TextView)view.findViewById(R.id.tv_tel);
        tv_tel_dial=(TextView)view.findViewById(R.id.tv_tel_dial);
        tv_gua_weight=(TextView)view.findViewById(R.id.tv_gua_weight);
        tv_shi_weight=(TextView)view.findViewById(R.id.tv_shi_weight);
        tv_gua_num=(TextView)view.findViewById(R.id.tv_gua_num);
        tv_shi_num=(TextView)view.findViewById(R.id.tv_shi_num);
        tv_all_price=(TextView)view.findViewById(R.id.tv_all_price);
        ll_photo_out=(LinearLayout)view. findViewById(R.id.ll_photo_out);
        ll_photo=(LinearLayout)view. findViewById(R.id.ll_photo);


        lv_goods=(ListView)findViewById(R.id.lv_goods);
        lv_goods.addHeaderView(view);
        tv_confirm=(TextView)findViewById(R.id.tv_confirm);

    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("运单详情");
        getRightTextView().setText("状态");
        waybilId=getIntent().getStringExtra("waybilId");
        orderId=getIntent().getStringExtra("orderId");
        type=getIntent().getIntExtra("type",0);
        if (type==0) {
            tv_confirm.setVisibility(View.GONE);
            getRightTextView().setVisibility(View.GONE);
        }else if(type==1){
            tv_confirm.setVisibility(View.GONE);
            getRightTextView().setVisibility(View.GONE);
        }else if(type==2){
            tv_confirm.setVisibility(View.GONE);
            getRightTextView().setVisibility(View.GONE);
        }else if(type==3){
            tv_confirm.setVisibility(View.VISIBLE);
            getRightTextView().setVisibility(View.VISIBLE);
        }else if(type==4){
            tv_confirm.setVisibility(View.VISIBLE);
            getRightTextView().setVisibility(View.VISIBLE);
        }else if(type==5){
            tv_confirm.setVisibility(View.VISIBLE);
            getRightTextView().setVisibility(View.VISIBLE);
        }else if(type==6){
            tv_confirm.setVisibility(View.VISIBLE);
            getRightTextView().setVisibility(View.VISIBLE);
        }
        getTopData();
        getGoodsData();
    }

    private void getTopData() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybilId);
        MyHttpUtil.selectWaybillInfo(activityContext,params, new MyCallback<ResultWaybilInfoTop>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ResultWaybilInfoTop result, int id) {
                if (result.getCode() == ConstUtil.OK ) {
                        updateUi(result.getData());
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }

    private void getGoodsData() {
        DialogUtil.showLoadingDialog(activityContext,"请求中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybilId);
        MyHttpUtil.selectByWaybillId (activityContext,params, new MyCallback<LookWaybillDetailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(LookWaybillDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK ) {
                        setGoodsAdapter(result.getData());
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }






    private void setGoodsAdapter(LookWaybillDetailData data) {
        List<LookWaybillDetailData.DataBean> ss = data.getData();
        GoodsForAssignWaybilDetailAdapter adapter=new GoodsForAssignWaybilDetailAdapter(activityContext,data.getData());
        lv_goods.setAdapter(adapter);
    }

    private void updateUi(final ResultWaybilInfoTop.DataBean waybildata) {
        if (waybildata==null)return;
        try {
            setTopUi(waybildata);
            setImageView(waybildata);

            tv_tel_dial.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtil.dial(activityContext,waybildata.getPhoneCall());
                }
            });
            tv_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activityContext, DeliveryOrderActivity.class);
                    intent.putExtra("driverId", waybildata.getPhoneCall() + "");
                    intent.putExtra("data", waybildata.getWaybillId() + "");
                    startActivity(intent);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private void setTopUi(ResultWaybilInfoTop.DataBean waybildata) {
        tv_waybill_no.setText(waybildata.getWaybillNo());
        tv_date.setText(waybildata.getOrderTime());
        tv_driver_name.setText(waybildata.getUsername());
        tv_plate_no.setText(waybildata.getPlateNumber());
        tv_tel.setText(StringUtil.handlePhoneNumShow(waybildata.getPhoneCall()));
        tv_gua_weight.setText(waybildata.getOriginalWeight()+"");
        if (waybildata.getSumDetailsWeight()!=0)
            tv_shi_weight.setText(waybildata.getSumDetailsWeight()+"");
        tv_gua_num.setText(waybildata.getOriginalNum()+"");
        if (waybildata.getSumDetailsNum()!=0)
            tv_shi_num.setText(waybildata.getSumDetailsNum()+"");
        tv_all_price.setText(waybildata.getSumPrice()+"");

        if ("2".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("待装货");
        }else if ("3".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("装货中");
        }else if ("4".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("运输中");
        }else if ("5".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("卸货中");
        }else if ("6".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("待收货");
        }else if ("7".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("已完成");
        }else if ("8".equals(waybildata.getWaybillStatus())){
            tv_order_status.setText("已取消");
        }

    }
    private int imageNum;
    private void setImageView(ResultWaybilInfoTop.DataBean waybildata) {
        if (ll_photo.getChildCount() > 0) {
            ll_photo.removeAllViews();
        }
        if(type==5 ||type==6){
            setImageWithDelete(waybildata);
        }else {
            setImageNoDelete(waybildata);
        }
    }

    private void setImageWithDelete(ResultWaybilInfoTop.DataBean waybildata) {
        if (waybildata != null && waybildata.getWaybillImagesList() != null && waybildata.getWaybillImagesList().size() > 0) {
            imageNum = waybildata.getWaybillImagesList().size();
            ll_photo_out.setVisibility(View.VISIBLE);

            for (final ResultWaybilInfoTop.DataBean.WaybillImagesListBean entity : waybildata.getWaybillImagesList()) {
                addView(entity, 0);
            }
            if (waybildata.getWaybillImagesList().size() < 8) {
                if (type == 5 || type == 6) {
                    //代运实发-运单列表 ，车队长分配给自己的单子或者自己接的单子进入
                    addView(null, 1);
                }
            }
        } else {
//            if (!StringUtil.isBlank(waybildata.getWaybillStatus())&& Integer.parseInt(waybildata.getWaybillStatus())>=4) {
            if (!StringUtil.isBlank(waybildata.getWaybillStatus())) {
                ll_photo_out.setVisibility(View.VISIBLE);
                addView(null, 1);
            } else {
                ll_photo_out.setVisibility(View.GONE);
            }
        }


    }

    private void setImageNoDelete(ResultWaybilInfoTop.DataBean waybildata) {
        if (waybildata!=null &&waybildata.getWaybillImagesList()!=null && waybildata.getWaybillImagesList().size()>0){
            ll_photo_out.setVisibility(View.VISIBLE);
            for (final ResultWaybilInfoTop.DataBean.WaybillImagesListBean entity:waybildata.getWaybillImagesList()){
                View view=View.inflate(activityContext,R.layout.home_item_imageview,null);
                ImageView imageView=(ImageView)view.findViewById(R.id.img_unload) ;
                BitmapUtil.showImgForNetPath(entity.getWaybillImages(),imageView);
                TextView tv_delete=(TextView)view.findViewById(R.id.tv_delete);
                tv_delete.setVisibility(View.GONE);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                view.setLayoutParams(layoutParams);
                ll_photo.addView(view); //动态添加图片
                //查看大图
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent=new Intent(activityContext, LookPhotoDetailActivity.class);
                        intent.putExtra("data",entity.getWaybillImages());
                        startActivity(intent);
                    }
                });
            }
        }else {
            ll_photo_out.setVisibility(View.GONE);
        }
    }



    private void addView(final ResultWaybilInfoTop.DataBean.WaybillImagesListBean entity, final int ifShowDelete) {
        //ifShowDelete ==0,显示删除小图片，
        View view = View.inflate(activityContext, R.layout.home_item_imageview, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.img_unload);
        TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(layoutParams);

        if (ifShowDelete == 0 && entity != null) {
            BitmapUtil.showImgForNetPath(entity.getWaybillImages(), imageView);
        } else {
            imageView.setImageResource(R.mipmap.upload);
        }


        if (ifShowDelete == 0 && (type == 5 || type == 6)) {
            tv_delete.setVisibility(View.VISIBLE);
        } else {
            tv_delete.setVisibility(View.GONE);
        }

        ll_photo.addView(view); //动态添加图片
        //查看大图
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ifShowDelete == 0) {
                    Intent intent = new Intent(activityContext, LookPhotoDetailActivity.class);
                    intent.putExtra("data", entity.getWaybillImages());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(activityContext, SureUnLoadOverActivity.class);
                    intent.putExtra("maxNum", 8 - imageNum);
                    intent.putExtra("ifChangeStatus",false);
                        intent.putExtra("waybillId",Integer.parseInt(waybilId));
                        intent.putExtra("fromlist", true);
                        intent.putExtra("personalOrder", false);
                    startActivity(intent);
                }
            }
        });
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = DialogUtil.myDialog(activityContext, "删除照片", "取消", "确定", "确定删除照片？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.dialog_btn_right) {
                            ArrayList<Integer> images = new ArrayList<Integer>();
                            images.add(entity.getWaybillId());
                            deleteWaybillImgById(images);
                        }
                        dialog.cancel();
                    }
                });
            }
        });


    }



    //删除卸货照片
    private void deleteWaybillImgById(ArrayList<Integer> imageId) {
        DialogUtil.showLoadingDialog(activityContext, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillImgIds", imageId);
        MyHttpUtil.deleteWaybillImgById(activityContext, params, new MyCallback<OrderDatailResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext, "删除成功");
                    getTopData();
                } else {
                    if (result.getMsg() != null)
                        PrintUtil.toast(activityContext, result.getMsg());
                }

            }
        });
    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void baseGoEnsure() {
//        mFragment.resetChoose();
       /* if (data!=null) {
            Intent intent = new Intent(activityContext, OrderStatusActivity.class);
            intent.putExtra("orderId", data.getOrderId() + "");
            intent.putExtra("type",0);
            intent.putExtra("data",data);
            startActivity(intent);
        }*/

        Intent intent = new Intent(activityContext, WaybilStatusActivity.class);
        intent.putExtra("waybilId", waybilId + "");
        startActivity(intent);
    }




    public void onEventMainThread(RefleshFragEvent event) {
        if (event.getIndex() == 3) {
            getTopData();
        }
    }


}
